﻿#include "butterfly.h"

#include <QApplication>
#include <QDesktopWidget>
#include <QList>
#include <QMouseEvent>
#include <QPainter>
#include <QRandomGenerator>
#include <QThread>
butterfly::butterfly(QWidget *parent) : QWidget(parent) {
  m_pixmap.load(":/1");
  setFixedSize(m_pixmap.size());
  startTimer(100);  //每100ms触发一次timerevent事件
}

void butterfly::fly() { fly(10, 30); }

void butterfly::fly(int min, int max) {
  m_index++;  // index 1、2 切换
  if (m_index > 2) {
    m_index = 1;
  }
  QString name = QString(":/%1").arg(m_index);
  m_pixmap.load(name);
  update();  //窗口刷新,触发paintevent事件

  //移动步长
  //随机数函数 qrand() 已废弃
  int stepX = QRandomGenerator::global()->bounded(min, max);
  int stepY = QRandomGenerator::global()->bounded(min, max);

  //新坐标点
  int curX = this->geometry().topLeft().x() + stepX;
  int curY = this->geometry().topLeft().y() + stepY;

  //判定是否已超出窗口
  QDesktopWidget *desk = QApplication::desktop();

  if (curX >= desk->screenGeometry().right()) {
    curX = desk->screenGeometry().left();
  }
  if (curY >= desk->screenGeometry().bottom()) {
    curY = desk->screenGeometry().top();
  }
  move(curX, curY);
}

void butterfly::paintEvent(QPaintEvent *ev) {
  QPainter p(this);
  p.drawPixmap(rect(), m_pixmap);
}

void butterfly::timerEvent(QTimerEvent *ev) { fly(); }

void butterfly::mousePressEvent(QMouseEvent *ev) {
  if (ev->button() == Qt::LeftButton) {  //获取距离鼠标点和图像左上角距离
    m_pt = ev->globalPos() - this->geometry().topLeft();
  }
}

void butterfly::mouseMoveEvent(QMouseEvent *ev) {
  if (ev->buttons() & Qt::LeftButton) {  //判断鼠标按键操作中是否包含左键
    this->move(ev->globalPos() - m_pt);
  }
}

void butterfly::enterEvent(QEvent *ev) {  //进入边缘时触发
  fly(-200, 200);
}  //图标躲避鼠标效果
